{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m"
     ]
    }
   ],
   "source": [
    "! pip install -qU memorizz yahooquery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "\n",
    "# Add the project root to the Python path\n",
    "project_root = os.path.abspath(os.path.join(os.getcwd(), \"..\", \"..\", \"..\"))\n",
    "sys.path.insert(0, project_root)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "# Function to securely get and set environment variables\n",
    "def set_env_securely(var_name, prompt):\n",
    "    value = getpass.getpass(prompt)\n",
    "    os.environ[var_name] = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"MONGODB_URI\", \"Enter your MongoDB URI: \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"OPENAI_API_KEY\", \"Enter your OpenAI API key: \")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Initalize a Memory Provider\n",
    "\n",
    "A Memory Provider is a core abstraction layer that manages the persistence, organization, and retrieval of all memory components within an agentic system. It serves as the central nervous system for memory management, providing standardized interfaces between AI agents and underlying storage technologies.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from src.memorizz.memory_provider.mongodb.provider import MongoDBConfig, MongoDBProvider\n",
    "\n",
    "# Create a memory provider\n",
    "mongodb_config = MongoDBConfig(uri=os.environ[\"MONGODB_URI\"])\n",
    "memory_provider = MongoDBProvider(mongodb_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "def get_weather(latitude, longitude):\n",
    "    response = requests.get(f\"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m\")\n",
    "    data = response.json()\n",
    "    return data['current']['temperature_2m']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22.7\n"
     ]
    }
   ],
   "source": [
    "latitude = 40.7128\n",
    "longitude = -74.0060\n",
    "weather = get_weather(latitude, longitude)\n",
    "print(weather)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import lru_cache\n",
    "from yahooquery import Ticker\n",
    "import time\n",
    "\n",
    "@lru_cache(maxsize=128)\n",
    "def _fetch_price(symbol: str) -> float:\n",
    "    \"\"\"\n",
    "    Internal helper to fetch the latest market price via yahooquery.\n",
    "    Caching helps avoid repeated hits for the same symbol.\n",
    "    \"\"\"\n",
    "    ticker = Ticker(symbol)\n",
    "    # This returns a dict keyed by symbol:\n",
    "    info = ticker.price or {}\n",
    "    # regularMarketPrice holds the current trading price\n",
    "    price = info.get(symbol.upper(), {}).get(\"regularMarketPrice\")\n",
    "    if price is None:\n",
    "        raise ValueError(f\"No price data for '{symbol}'\")\n",
    "    return price\n",
    "\n",
    "def get_stock_price(\n",
    "    symbol: str,\n",
    "    currency: str = \"USD\",\n",
    "    retry: int = 3,\n",
    "    backoff: float = 0.5\n",
    ") -> str:\n",
    "    \"\"\"\n",
    "    Get the current stock price for a given symbol using yahooquery,\n",
    "    with simple retry/backoff to handle occasional rate-limits.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    symbol : str\n",
    "        Stock ticker, e.g. \"AAPL\"\n",
    "    currency : str, optional\n",
    "        Currency code (Currently informational only; yahooquery returns native)\n",
    "    retry : int, optional\n",
    "        Number of retries on failure (default: 3)\n",
    "    backoff : float, optional\n",
    "        Backoff factor in seconds between retries (default: 0.5s)\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    str\n",
    "        e.g. \"The current price of AAPL is 172.34 USD.\"\n",
    "    \"\"\"\n",
    "    symbol = symbol.upper()\n",
    "    last_err = None\n",
    "    for attempt in range(1, retry + 1):\n",
    "        try:\n",
    "            price = _fetch_price(symbol)\n",
    "            return f\"The current price of {symbol} is {price:.2f} {currency.upper()}.\"\n",
    "        except Exception as e:\n",
    "            last_err = e\n",
    "            # simple backoff\n",
    "            time.sleep(backoff * attempt)\n",
    "    # if we get here, all retries failed\n",
    "    raise RuntimeError(f\"Failed to fetch price for '{symbol}' after {retry} attempts: {last_err}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The current price of AAPL is 201.08 USD.\n"
     ]
    }
   ],
   "source": [
    "print(get_stock_price(\"AAPL\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'686016436724e210da3d0b6f'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from src.memorizz import Toolbox\n",
    "# Create a Toolbox instance\n",
    "weather_toolbox = Toolbox(memory_provider=memory_provider)\n",
    "stock_toolbox = Toolbox(memory_provider=memory_provider)\n",
    "# Register the functions with the Toolbox\n",
    "# These tools are now stored in the `ToolBox` store within the storage provider\n",
    "weather_toolbox.register_tool(get_weather)\n",
    "stock_toolbox.register_tool(get_stock_price)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:Loading 1 available tools from toolbox (skipping database-only tools)\n",
      "INFO:src.memorizz.memagent:Memagent None updated in the memory provider\n",
      "INFO:src.memorizz.memagent:Memagent 6860164a6724e210da3d0b70 saved in the memory provider\n",
      "INFO:src.memorizz.memagent:{\n",
      "    \"model\": null,\n",
      "    \"tools\": [\n",
      "        {\n",
      "            \"_id\": \"6860163f6724e210da3d0b6e\",\n",
      "            \"name\": \"get_weather\",\n",
      "            \"description\": \"Retrieve the current weather information for a specific location identified by latitude and longitude coordinates. This function accesses weather data from a reliable source and provides insights into temperature, humidity, wind speed, and other meteorological conditions.\",\n",
      "            \"parameters\": [\n",
      "                {\n",
      "                    \"name\": \"latitude\",\n",
      "                    \"description\": \"The geographical latitude of the location. It should be a decimal number ranging from -90.0 to 90.0, with positive values indicating north of the equator and negative values south.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": true\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"longitude\",\n",
      "                    \"description\": \"The geographical longitude of the location. It should be a decimal number ranging from -180.0 to 180.0, with positive values indicating east of the Prime Meridian and negative values west.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": true\n",
      "                }\n",
      "            ],\n",
      "            \"strict\": true\n",
      "        }\n",
      "    ],\n",
      "    \"persona\": null,\n",
      "    \"instruction\": \"You are a weather specialist focused on weather data gathering and analysis.\",\n",
      "    \"memory_mode\": \"general\",\n",
      "    \"max_steps\": 20,\n",
      "    \"memory_ids\": [],\n",
      "    \"tool_access\": \"private\",\n",
      "    \"long_term_memory_ids\": null,\n",
      "    \"delegates\": null,\n",
      "    \"_id\": \"6860164a6724e210da3d0b70\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "MemAgent(agent_id=6860164a6724e210da3d0b70, memory_provider=<src.memorizz.memory_provider.mongodb.provider.MongoDBProvider object at 0x7fb9a8605880>)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from src.memorizz import MemAgent\n",
    "\n",
    "# Create specialized agents\n",
    "weather_agent = MemAgent(\n",
    "    memory_provider=memory_provider,\n",
    "    instruction=\"You are a weather specialist focused on weather data gathering and analysis.\"\n",
    ")\n",
    "weather_agent.add_tool(toolbox=weather_toolbox, persist=True)\n",
    "\n",
    "weather_agent.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:Loading 1 available tools from toolbox (skipping database-only tools)\n",
      "INFO:src.memorizz.memagent:Memagent None updated in the memory provider\n",
      "INFO:src.memorizz.memagent:Memagent 6860164a6724e210da3d0b71 saved in the memory provider\n",
      "INFO:src.memorizz.memagent:{\n",
      "    \"model\": null,\n",
      "    \"tools\": [\n",
      "        {\n",
      "            \"_id\": \"686016436724e210da3d0b6f\",\n",
      "            \"name\": \"get_stock_price\",\n",
      "            \"description\": \"Get the current stock price for a specified stock symbol using the yahooquery API. This function incorporates a retry mechanism with exponential backoff to handle occasional rate-limit issues encountered during API calls. It captures and returns the latest stock price as a formatted string.\",\n",
      "            \"parameters\": [\n",
      "                {\n",
      "                    \"name\": \"symbol\",\n",
      "                    \"description\": \"String representing the stock ticker symbol. This parameter is required and is used to identify the stock for which the price is being fetched, such as 'AAPL'.\",\n",
      "                    \"type\": \"string\",\n",
      "                    \"required\": true\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"currency\",\n",
      "                    \"description\": \"Optional string specifying the currency code in which the stock price is displayed. While this is currently informational, as yahooquery returns the price in the stock's native currency, it defaults to 'USD'.\",\n",
      "                    \"type\": \"string\",\n",
      "                    \"required\": false\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"retry\",\n",
      "                    \"description\": \"Optional integer that specifies the number of retry attempts if the API call fails. It defaults to 3 retries, enabling a robust attempt to fetch data in case of minor network disruptions or rate-limits.\",\n",
      "                    \"type\": \"integer\",\n",
      "                    \"required\": false\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"backoff\",\n",
      "                    \"description\": \"Optional float representing the backoff factor in seconds between retry attempts. This provides a pause before reattempting the API call, with a default value of 0.5 seconds, to help mitigate rate-limit issues systematically.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": false\n",
      "                }\n",
      "            ],\n",
      "            \"strict\": true\n",
      "        }\n",
      "    ],\n",
      "    \"persona\": null,\n",
      "    \"instruction\": \"You are a stock specialist focused on stock data gathering and analysis.\",\n",
      "    \"memory_mode\": \"general\",\n",
      "    \"max_steps\": 20,\n",
      "    \"memory_ids\": [],\n",
      "    \"tool_access\": \"private\",\n",
      "    \"long_term_memory_ids\": null,\n",
      "    \"delegates\": null,\n",
      "    \"_id\": \"6860164a6724e210da3d0b71\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "MemAgent(agent_id=6860164a6724e210da3d0b71, memory_provider=<src.memorizz.memory_provider.mongodb.provider.MongoDBProvider object at 0x7fb9a8605880>)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stock_agent = MemAgent(\n",
    "    memory_provider=memory_provider,\n",
    "    instruction=\"You are a stock specialist focused on stock data gathering and analysis.\"\n",
    ")\n",
    "stock_agent.add_tool(toolbox=stock_toolbox)\n",
    "stock_agent.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:Memagent 6860164a6724e210da3d0b72 saved in the memory provider\n",
      "INFO:src.memorizz.memagent:{\n",
      "    \"model\": null,\n",
      "    \"tools\": [\n",
      "        {\n",
      "            \"_id\": \"6860163f6724e210da3d0b6e\",\n",
      "            \"name\": \"get_weather\",\n",
      "            \"description\": \"Retrieve the current weather information for a specific location identified by latitude and longitude coordinates. This function accesses weather data from a reliable source and provides insights into temperature, humidity, wind speed, and other meteorological conditions.\",\n",
      "            \"parameters\": [\n",
      "                {\n",
      "                    \"name\": \"latitude\",\n",
      "                    \"description\": \"The geographical latitude of the location. It should be a decimal number ranging from -90.0 to 90.0, with positive values indicating north of the equator and negative values south.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": true\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"longitude\",\n",
      "                    \"description\": \"The geographical longitude of the location. It should be a decimal number ranging from -180.0 to 180.0, with positive values indicating east of the Prime Meridian and negative values west.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": true\n",
      "                }\n",
      "            ],\n",
      "            \"strict\": true\n",
      "        }\n",
      "    ],\n",
      "    \"persona\": null,\n",
      "    \"instruction\": \"You are a weather specialist focused on weather data gathering and analysis.\",\n",
      "    \"memory_mode\": \"general\",\n",
      "    \"max_steps\": 20,\n",
      "    \"memory_ids\": [],\n",
      "    \"tool_access\": \"private\",\n",
      "    \"long_term_memory_ids\": null,\n",
      "    \"delegates\": null,\n",
      "    \"_id\": \"6860164a6724e210da3d0b72\"\n",
      "}\n",
      "INFO:src.memorizz.memagent:Memagent 6860164a6724e210da3d0b73 saved in the memory provider\n",
      "INFO:src.memorizz.memagent:{\n",
      "    \"model\": null,\n",
      "    \"tools\": [\n",
      "        {\n",
      "            \"_id\": \"686016436724e210da3d0b6f\",\n",
      "            \"name\": \"get_stock_price\",\n",
      "            \"description\": \"Get the current stock price for a specified stock symbol using the yahooquery API. This function incorporates a retry mechanism with exponential backoff to handle occasional rate-limit issues encountered during API calls. It captures and returns the latest stock price as a formatted string.\",\n",
      "            \"parameters\": [\n",
      "                {\n",
      "                    \"name\": \"symbol\",\n",
      "                    \"description\": \"String representing the stock ticker symbol. This parameter is required and is used to identify the stock for which the price is being fetched, such as 'AAPL'.\",\n",
      "                    \"type\": \"string\",\n",
      "                    \"required\": true\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"currency\",\n",
      "                    \"description\": \"Optional string specifying the currency code in which the stock price is displayed. While this is currently informational, as yahooquery returns the price in the stock's native currency, it defaults to 'USD'.\",\n",
      "                    \"type\": \"string\",\n",
      "                    \"required\": false\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"retry\",\n",
      "                    \"description\": \"Optional integer that specifies the number of retry attempts if the API call fails. It defaults to 3 retries, enabling a robust attempt to fetch data in case of minor network disruptions or rate-limits.\",\n",
      "                    \"type\": \"integer\",\n",
      "                    \"required\": false\n",
      "                },\n",
      "                {\n",
      "                    \"name\": \"backoff\",\n",
      "                    \"description\": \"Optional float representing the backoff factor in seconds between retry attempts. This provides a pause before reattempting the API call, with a default value of 0.5 seconds, to help mitigate rate-limit issues systematically.\",\n",
      "                    \"type\": \"number\",\n",
      "                    \"required\": false\n",
      "                }\n",
      "            ],\n",
      "            \"strict\": true\n",
      "        }\n",
      "    ],\n",
      "    \"persona\": null,\n",
      "    \"instruction\": \"You are a stock specialist focused on stock data gathering and analysis.\",\n",
      "    \"memory_mode\": \"general\",\n",
      "    \"max_steps\": 20,\n",
      "    \"memory_ids\": [],\n",
      "    \"tool_access\": \"private\",\n",
      "    \"long_term_memory_ids\": null,\n",
      "    \"delegates\": null,\n",
      "    \"_id\": \"6860164a6724e210da3d0b73\"\n",
      "}\n",
      "INFO:src.memorizz.memagent:Memagent 6860164b6724e210da3d0b74 saved in the memory provider\n",
      "INFO:src.memorizz.memagent:{\n",
      "    \"model\": null,\n",
      "    \"tools\": null,\n",
      "    \"persona\": null,\n",
      "    \"instruction\": \"You coordinate complex tasks by delegating to specialized agents.\",\n",
      "    \"memory_mode\": \"general\",\n",
      "    \"max_steps\": 20,\n",
      "    \"memory_ids\": [],\n",
      "    \"tool_access\": \"private\",\n",
      "    \"long_term_memory_ids\": null,\n",
      "    \"delegates\": [\n",
      "        \"6860164a6724e210da3d0b70\",\n",
      "        \"6860164a6724e210da3d0b71\"\n",
      "    ],\n",
      "    \"_id\": \"6860164b6724e210da3d0b74\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "MemAgent(agent_id=6860164b6724e210da3d0b74, memory_provider=<src.memorizz.memory_provider.mongodb.provider.MongoDBProvider object at 0x7fb9a8605880>)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Create root agent with delegates\n",
    "coordinator = MemAgent(\n",
    "    memory_provider=memory_provider,\n",
    "    delegates=[weather_agent, stock_agent],\n",
    "    instruction=\"You coordinate complex tasks by delegating to specialized agents.\"\n",
    ")\n",
    "\n",
    "coordinator.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:AGENT RUN START: Agent 6860164b6724e210da3d0b74 executing query: Give me the weather in San Francisco and then the ...\n",
      "INFO:src.memorizz.memagent:AGENT RUN DEBUG: Agent has memory_ids: []\n",
      "INFO:src.memorizz.memagent:Initialized orchestrator for agent 6860164b6724e210da3d0b74 with 2 delegates\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Starting multi-agent workflow for query: Give me the weather in San Francisco and then the stock price of Apple\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Root agent ID: 6860164b6724e210da3d0b74\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Number of delegates: 2\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Delegate IDs: ['6860164a6724e210da3d0b72', '6860164a6724e210da3d0b73']\n",
      "INFO:src.memorizz.multi_agent_orchestrator:No existing session found, creating new root-level shared session\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Created new shared memory session: 6860164b6724e210da3d0b76\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Initial delegates: ['6860164a6724e210da3d0b72', '6860164a6724e210da3d0b73']\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Added shared memory ID 6860164b6724e210da3d0b76 to root agent's memory_ids array\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Persisted memory_ids to storage: success\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Added shared memory ID 6860164b6724e210da3d0b76 to delegate agent 6860164a6724e210da3d0b72's memory_ids array\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Persisted delegate 6860164a6724e210da3d0b72 memory_ids to storage: success\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Added shared memory ID 6860164b6724e210da3d0b76 to delegate agent 6860164a6724e210da3d0b73's memory_ids array\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Persisted delegate 6860164a6724e210da3d0b73 memory_ids to storage: success\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164b6724e210da3d0b74, entry_type: workflow_start\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 0 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 6860164b6724e210da3d0b77\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 1 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Starting task decomposition...\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Task decomposition considering hierarchy: {'root_agent': '6860164b6724e210da3d0b74', 'delegate_agents': ['6860164a6724e210da3d0b72', '6860164a6724e210da3d0b73'], 'sub_agents': [], 'total_agents': 3, 'session_status': 'active', 'created_at': '2025-06-28T17:20:27.120662'}\n",
      "INFO:src.memorizz.task_decomposition:Starting task decomposition for query: Give me the weather in San Francisco and then the stock price of Apple\n",
      "INFO:src.memorizz.task_decomposition:Number of delegates: 2\n",
      "INFO:src.memorizz.task_decomposition:Analyzing delegate capabilities...\n",
      "INFO:src.memorizz.task_decomposition:Analyzed capabilities for 2 agents\n",
      "INFO:src.memorizz.task_decomposition:Creating decomposition prompt...\n",
      "INFO:src.memorizz.task_decomposition:Calling LLM for task decomposition...\n",
      "INFO:src.memorizz.task_decomposition:LLM response received: [\n",
      "    {\n",
      "        \"task_id\": \"task_1\",\n",
      "        \"description\": \"Retrieve the current weather information for San Francisco using its latitude and longitude coordinates.\",\n",
      "        \"assigned_agent_id\": \"68...\n",
      "INFO:src.memorizz.task_decomposition:Parsing decomposition response...\n",
      "INFO:src.memorizz.task_decomposition:Successfully parsed 2 sub-tasks\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Decomposed into 2 tasks for 3 total agents\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Task decomposition resulted in 2 sub-tasks\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164b6724e210da3d0b74, entry_type: task_decomposition\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 1 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 6860164c6724e210da3d0b78\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 2 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Executing 2 sub-tasks in parallel...\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164a6724e210da3d0b72, entry_type: task_start\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 2 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 6860164d6724e210da3d0b79\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 3 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.memagent:AGENT RUN START: Agent 6860164a6724e210da3d0b72 executing query: Retrieve the current weather information for San F...\n",
      "INFO:src.memorizz.memagent:AGENT RUN DEBUG: Agent has memory_ids: ['6860164b6724e210da3d0b76']\n",
      "INFO:src.memorizz.memagent:EXPORT DEBUG: About to export monitoring files for agent 6860164a6724e210da3d0b72\n",
      "INFO:src.memorizz.memagent:EXPORT DEBUG: is_multi_agent = True (mode=False, delegates=0, has_session=True)\n",
      "INFO:src.memorizz.memagent:ABOUT TO CALL _export_multi_agent_logs for agent 6860164a6724e210da3d0b72\n",
      "INFO:src.memorizz.memagent:ENTERING _export_multi_agent_logs for agent 6860164a6724e210da3d0b72\n",
      "INFO:src.memorizz.memagent:Multi-agent log export check for agent 6860164a6724e210da3d0b72:\n",
      "INFO:src.memorizz.memagent:  - is_multi_agent_mode: False\n",
      "INFO:src.memorizz.memagent:  - delegates count: 0\n",
      "INFO:src.memorizz.memagent:  - memory_ids: ['6860164b6724e210da3d0b76']\n",
      "INFO:src.memorizz.memagent:  - has_shared_memory_ids: True\n",
      "INFO:src.memorizz.memagent:  - Final is_multi_agent: True\n",
      "INFO:src.memorizz.memagent:Exported multi-agent logs for agent 6860164a6724e210da3d0b72 to multi_agent_logs/\n",
      "INFO:src.memorizz.memagent:COMPLETED _export_multi_agent_logs call for agent 6860164a6724e210da3d0b72\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164a6724e210da3d0b72, entry_type: task_completion\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 3 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 686016516724e210da3d0b7f\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 4 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164a6724e210da3d0b73, entry_type: task_start\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 4 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 686016516724e210da3d0b80\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 5 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.memagent:AGENT RUN START: Agent 6860164a6724e210da3d0b73 executing query: Get the current stock price for Apple (AAPL) using...\n",
      "INFO:src.memorizz.memagent:AGENT RUN DEBUG: Agent has memory_ids: ['6860164b6724e210da3d0b76']\n",
      "INFO:src.memorizz.memagent:EXPORT DEBUG: About to export monitoring files for agent 6860164a6724e210da3d0b73\n",
      "INFO:src.memorizz.memagent:EXPORT DEBUG: is_multi_agent = True (mode=False, delegates=0, has_session=True)\n",
      "INFO:src.memorizz.memagent:ABOUT TO CALL _export_multi_agent_logs for agent 6860164a6724e210da3d0b73\n",
      "INFO:src.memorizz.memagent:ENTERING _export_multi_agent_logs for agent 6860164a6724e210da3d0b73\n",
      "INFO:src.memorizz.memagent:Multi-agent log export check for agent 6860164a6724e210da3d0b73:\n",
      "INFO:src.memorizz.memagent:  - is_multi_agent_mode: False\n",
      "INFO:src.memorizz.memagent:  - delegates count: 0\n",
      "INFO:src.memorizz.memagent:  - memory_ids: ['6860164b6724e210da3d0b76']\n",
      "INFO:src.memorizz.memagent:  - has_shared_memory_ids: True\n",
      "INFO:src.memorizz.memagent:  - Final is_multi_agent: True\n",
      "INFO:src.memorizz.memagent:Exported multi-agent logs for agent 6860164a6724e210da3d0b73 to multi_agent_logs/\n",
      "INFO:src.memorizz.memagent:COMPLETED _export_multi_agent_logs call for agent 6860164a6724e210da3d0b73\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164a6724e210da3d0b73, entry_type: task_completion\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 5 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 686016556724e210da3d0b86\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 6 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Sub-task execution completed with 2 results\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Starting result consolidation...\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Consolidation completed: Here is the consolidated response to your query:\n",
      "\n",
      "- The current weather in San Francisco (latitude: ...\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Adding blackboard entry - memory_id: 6860164b6724e210da3d0b76, agent_id: 6860164b6724e210da3d0b74, entry_type: workflow_complete\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Retrieved session with 6 existing entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Created blackboard entry with memory_id: 686016586724e210da3d0b87\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Added entry to session blackboard, now has 7 entries\n",
      "INFO:src.memorizz.shared_memory.shared_memory:Memory provider update result: True\n",
      "INFO:src.memorizz.multi_agent_orchestrator:Multi-agent workflow completed successfully\n"
     ]
    }
   ],
   "source": [
    "# Execute multi-agent workflow\n",
    "result = coordinator.run(\"Give me the weather in San Francisco and then the stock price of Apple\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Here is the consolidated response to your query:\\n\\n- The current weather in San Francisco (latitude: 37.7749, longitude: -122.4194) is 16.8°C.\\n- The current stock price for Apple (AAPL) is $201.08 USD.\\n\\nIf you need more detailed weather information (such as humidity or wind speed) or more details about Apple's stock performance (such as recent price history), please let me know!\\n\\nThere are no conflicting results, and all aspects of your request have been addressed. No additional steps are needed unless you require further details.\""
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "memorizz",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
